import { AppTask } from "../../app.task.class";
import { HealthCheckTask } from "./health.check.class";
import { Subject } from "rxjs";
import { V3proSubjectMessage } from "../model/v3pro.model";

/**
 * 健康检查任务服务
 */
export class HealthCheckServer extends AppTask {
  /**
   * 构造函数
   * @param __healthTask 健康检查任务
   * @param __observable 可观察对象
   */
  constructor(
    private __healthTask: new () => HealthCheckTask,
    private __observable: Subject<V3proSubjectMessage>,
  ) {
    super();
  }

  __pause(): Promise<boolean> {
    return Promise.resolve(false);
  }

  __restore(): Promise<boolean> {
    return Promise.resolve(false);
  }

  /**
   * 定时器
   * @private
   */
  private __intervalTimer: any;

  /**
   * 任务
   */
  async __run(): Promise<void> {
    this.__runTask().then();
    await this.__await();
  }

  /**
   * 具体检查
   * @private
   */
  private async __runTask() {
    const task = new this.__healthTask();
    task.setObservable(this.__observable);
    if (this.isStopped()) return;
    await task.start();
    this.__intervalTimer = setTimeout(() => {
      this.__runTask().then();
    }, task.getInterval());
  }

  __stop(): Promise<boolean> {
    clearInterval(this.__intervalTimer);
    return Promise.resolve(false);
  }
}
